package com.dianganjiao.lib.http;


import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.dianganjiao.lib.AppConstant;
import com.dianganjiao.lib.base.DataBean;
import com.dianganjiao.lib.bean.TokenBean;
import com.dianganjiao.lib.event.LoginEvent;
import com.dianganjiao.lib.util.Loog;
import com.dianganjiao.lib.util.SpUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Copyright：
 * Created by wxl on 2020/7/15 16:45
 * Description：
 * Modify time：
 * Modified by：
 */
public class AccessTokenInterceptor implements Interceptor {

    private String resultStr;

    @Override
    public Response intercept(Chain chain) throws IOException {
        //获取原先的请求对象
        Request request = chain.request();
        request = addGetBaseParams(request);
        Response response = chain.proceed(request);
        MediaType mediaType = response.body().contentType();
        if (isTokenExpired(response)) {
            //同步请求方式，获取最新的Token
           // Log.e("OkHttpManager", "静默自动刷新Token,然后重新请求数据");
            //同步请求方式，获取最新的Token
            String newSession = getNewToken();
            //使用新的Token，创建新的请求
            if (null != newSession && newSession.length() > 0) {
                Loog.Companion.e("重新请求："+newSession);
                Request newRequest = chain.request()
                        .newBuilder()
                        .header("Authorization", newSession)
                        .header("Connection", "keep-alive")
                        .build();
                //重新请求上次的接口
                return chain.proceed(newRequest.newBuilder().build());
            }

        }

        return response.newBuilder().body(ResponseBody.create(mediaType, resultStr)).build();
    }


    String getNewToken() {

        /**
         * 必须使用同步请求
         */
        String url = AppConstant.Companion.getBaseUrl() + "auth/oauth/token";
        //Log.e("OkHttpManager", "重新请求---" + url);
        OkHttpClient client = new OkHttpClient();

        RequestBody formBody = new FormBody.Builder()
                .add("client_id", "client-app")
                .add("client_secret", "123456")
                .add("grant_type", "refresh_token")
                .add("password", "123456")
                .add("refresh_token", SpUtil.Companion.getSp().getString("refreshToken"))
                .build();
        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/x-www-from-urlencoded")
                .post(formBody)
                .url(url)
                .build();
        okhttp3.Call call = client.newCall(request);

        try {
            Response response = call.execute();
            ResponseBody body = response.body();
            if(body != null) {
                String string = body.string();
               // Log.e("OkHttpManager", "刷新token返回：" + string);
                DataBean data = JSONObject.parseObject(string,DataBean.class);
                if (data.getCode() != 200) {
                    EventBus.getDefault().post(new LoginEvent());
                } else {
                    TokenBean token = JSONObject.parseObject(data.getData(), TokenBean.class);
                    if (TextUtils.isEmpty(token.getToken())) {
                        EventBus.getDefault().post(new LoginEvent());
                    } else {
                        SpUtil.Companion.getSp().put("refreshToken", token.getRefreshToken());
                        SpUtil.Companion.getSp().put("token", token.getTokenHead() + token.getToken());
                    }
                }
            } else  {
                EventBus.getDefault().post(new LoginEvent());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return SpUtil.Companion.getSp().getString("token");
    }

    /**
     * 根据Response，判断Token是否失效
     *
     * @param response
     * @return
     */
    private boolean isTokenExpired(Response response) {
        try {
            resultStr = response.body().string();
            DataBean requestCode = JSONObject.parseObject(resultStr, DataBean.class);
            if (requestCode.getCode() == 401) {
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 添加GET方法基础参数
     *
     * @param request
     * @return
     */
    private Request addGetBaseParams(Request request) {

        HttpUrl.Builder builder = request.url()
                .newBuilder();

//        if (!TextUtils.isEmpty(SpUtil.Companion.getSp().getString("token"))) {
//            builder.addQueryParameter("Authorization", SpUtil.Companion.getSp().getString("token"));//平台号
//        }

        HttpUrl httpUrl = builder.build();
        Loog.Companion.d("Authorization:" + SpUtil.Companion.getSp().getString("token"));
        request = request.newBuilder()
                .header("Connection", "keep-alive")
                .header("Authorization", SpUtil.Companion.getSp().getString("token"))
                .url(httpUrl)
                .build();

        return request;
    }

}
